#!/usr/bin/env python3
"""
结果显示视图组件
"""
import os
import sys
from typing import List, Optional

# 添加项目根目录到路径
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))

from PySide6.QtWidgets import (
    QWidget,
    QVBoxLayout,
    QLabel,
    QScrollArea,
    QFrame,
    QGridLayout,
)
from PySide6.QtGui import QPixmap, QImage
from PySide6.QtCore import Qt, Signal

from src.utils.image_recognition import RecognitionResult


class ResultView(QWidget):
    """识别结果显示组件"""

    result_selected = Signal(RecognitionResult)  # 结果被选中的信号

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setup_ui()
        self.results = []

    def setup_ui(self):
        """设置UI组件"""
        layout = QVBoxLayout(self)
        
        # 结果标题
        self.title_label = QLabel("识别结果")
        self.title_label.setStyleSheet("font-weight: bold; font-size: 14px;")
        layout.addWidget(self.title_label)
        
        # 结果容器（使用滚动区域）
        self.results_container = QFrame()
        self.results_layout = QGridLayout(self.results_container)
        
        self.scroll_area = QScrollArea()
        self.scroll_area.setWidgetResizable(True)
        self.scroll_area.setWidget(self.results_container)
        
        layout.addWidget(self.scroll_area)
        
        # 无结果提示
        self.no_results_label = QLabel("无识别结果")
        self.no_results_label.setAlignment(Qt.AlignCenter)
        self.no_results_label.setStyleSheet("color: gray; font-style: italic;")
        self.results_layout.addWidget(self.no_results_label, 0, 0)

    def display_results(self, results: List[RecognitionResult]):
        """显示识别结果"""
        # 清空现有结果
        self.clear_results()
        self.results = results
        
        # 如果没有结果，显示提示信息
        if not results:
            self.no_results_label.setVisible(True)
            return
        
        # 隐藏提示信息
        self.no_results_label.setVisible(False)
        
        # 显示结果
        for idx, result in enumerate(results):
            # 创建结果项
            result_frame = QFrame()
            result_frame.setFrameStyle(QFrame.StyledPanel)
            result_layout = QVBoxLayout(result_frame)
            
            # 标题（模板名称和置信度）
            name_label = QLabel(f"{result.template_name} ({result.confidence:.2f})")
            name_label.setStyleSheet("font-weight: bold;")
            result_layout.addWidget(name_label)
            
            # 位置信息
            loc_label = QLabel(f"位置: ({result.location[0]}, {result.location[1]})")
            result_layout.addWidget(loc_label)
            
            # 如果有源图像，可以显示匹配区域的缩略图
            # 此处省略图像显示代码
            
            # 添加到网格布局
            row, col = divmod(idx, 2)
            self.results_layout.addWidget(result_frame, row, col)

    def clear_results(self):
        """清除所有结果"""
        # 清空布局
        while self.results_layout.count():
            item = self.results_layout.takeAt(0)
            if item.widget():
                item.widget().deleteLater()
        
        self.no_results_label = QLabel("无识别结果")
        self.no_results_label.setAlignment(Qt.AlignCenter)
        self.no_results_label.setStyleSheet("color: gray; font-style: italic;")
        self.results_layout.addWidget(self.no_results_label, 0, 0)
        
        self.results = [] 